import { download, httpGet, httpPost, upload } from '@/http'
import { services } from '@/config'
import { computeFileHash } from '@/components/uploader/js/hash'

export const getFiles = ({ current, size, descs, ascs, example }) =>
  httpPost(`${services.commonService}file/getFiles`, { current, size, descs, ascs, example })
export const getMyFiles = ({ current, size, descs, ascs, example }) =>
  httpPost(`${services.commonService}file/getMyFiles`, { current, size, descs, ascs, example })
export const getDirectories = ({ descs, ascs, example }) =>
  httpPost(`${services.commonService}file/getDirectories`, { descs, ascs, example })
export const copyFiles = ({ fileIds, directoryId }) =>
  httpPost(`${services.commonService}file/copyFiles`, { fileIds, directoryId }, true)
export const moveFiles = ({ fileIds, directoryId }) =>
  httpPost(`${services.commonService}file/moveFiles`, { fileIds, directoryId }, true)
export const newDirectory = ({ directoryId, name, ...rest }) =>
  httpPost(`${services.commonService}file/newDirectory`, { directoryId, name, ...rest })
export const deleteFile = fileIds => httpPost(`${services.commonService}file/delete`, { fileIds }, true)
export const renameFile = (fileId, newName) =>
  httpPost(`${services.commonService}file/rename`, { fileId, newName }, true)
export const downloadFiles = ids => download(`${services.commonService}file/download`, { data: { ids } })
export const uploadFile = async (url, file, options = {}) => {
  options.onprogress?.({ percent: 0 })
  const identifier = await computeFileHash(file, {
    onUpdate: (currentChunk, totalChunk) => {
      options.onprogress?.({ percent: ((currentChunk / totalChunk) * 50).toFixed(0) })
    }
  })
  options.data = options.data || {}

  options.data.filename = file.name
  options.data.totalSize = file.size
  options.data.identifier = identifier

  const res = await checkFile({ ...options.data })

  if (res.data.data.fileUploaded) {
    options.onprogress?.({ percent: 100 })
    res.data.data = res.data.data.fileDescription
    return res
  }
  const onprogressFn = options.onprogress

  if (onprogressFn) {
    options.onprogress = e => {
      onprogressFn({ percent: 50 + (e.percent * 0.5).toFixed(0) })
    }
  }

  return upload(url, file, options)
}
export const checkFile = ({ identifier, ...rest }) =>
  httpGet(`${services.commonService}file/chunk`, { identifier, ...rest })
